# -*- coding: utf-8 -*-

import random
import xml.dom.minidom as parser 

num = 0

class Group:
    def calcDiff(this, other):
        diff = this.score - other.score
        if diff < 0:
            diff = -diff
        return diff

    def __init__(this):
        this.score = 0
        this.members = []

    def __unicode__(this):
        s = u"分组(%d):\n" % (this.score)
        for m in this.members:
            s += m.__unicode__() + '\n'
        return s

class Race:
    def getScore(this, num):
        if num <= 2:
            return int(this.singles)
        elif num <= 4:
            return int(this.doubles)
        else:
            return int(this.team)

    def __unicode__(this):
        return "%s %d" % (this.id, this.singles)

class Member:
    def isEntry(this):
        return int(this.entry)

    def getScore(this, num):
        return this.races[0].getScore(num)

    def appendRace(this, race):
        this.races = []
        this.races.append(race)

    def __unicode__(this):
        return "%s[%s:%d]: %s" % (this.name, this.races[0].id, this.getScore(num), this.id)

def parseNode(node):
    member = Member()
    member.name = node.getAttribute("name")
    member.id = node.getAttribute("id")
    member.entry = node.getAttribute("entry")
    races = node.getElementsByTagName("race")
    for r in races:
        race = Race()
        race.id = r.getAttribute("id")
        race.singles = r.getAttribute("singles")
        race.doubles = r.getAttribute("doubles")
        race.team = r.getAttribute("team")
        member.appendRace(race)
    return member

def loadConfig(fileName, tagName):
    members = []
    dom = parser.parse(fileName)
    nodeList = dom.getElementsByTagName(tagName)
    for node in nodeList:
        member = parseNode(node)
        if member.isEntry():
            members.append(member)

    return members

def statTotalScore(members):
    defRace = 0
    totalScore = 0
    num = len(members)
    for member in members:
        totalScore += member.getScore(num)

    return totalScore

def groupByLevel(members):
    groupA = Group()
    groupB = Group()
    idx = 0
    totalScore = statTotalScore(members)
    for member in members:
        rd = random.random()
        if rd > 0.5:
            g = groupA
            if g.score >= totalScore / 2:
                g = groupB
        else:
            g = groupB
            if g.score >= totalScore / 2:
                g = groupA

        g.score += member.getScore(num)
        g.members.append(member)

    diff = groupA.calcDiff(groupB)
    if diff > num * 5:
        return groupByLevel(members)

    return [groupA, groupB]

def showGroup(group):
    for g in group:
        print g.__unicode__()

if __name__ == '__main__':
    random.seed()
    persons = loadConfig("list.xml", "member")
    group = groupByLevel(persons)
    showGroup(group)
